package com.exception.handler;

import com.exception.exception.MyException;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@Component
public class MyExceptionHandler extends AbstractHandlerExceptionResolver {

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        if (e instanceof MyException) {
            try {
                MyException ex = (MyException) e;
                String message = ex.getCode() + ex.getMesssage();
                response.sendError(ex.getHttpStatus().value(), message);
                return new ModelAndView();
            } catch (IOException exception) {
                System.out.println(exception.getMessage());
            }
        }
        return null;
    }

    public void MyExceptionHandler() {
        setOrder(Ordered.HIGHEST_PRECEDENCE);
    }
}
